package com.funo.core.base;

import java.lang.reflect.Type;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.hibernate.collection.internal.PersistentList;
import org.hibernate.proxy.HibernateProxy;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.funo.main.entities.User;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public abstract class BaseCtrler {
	@ExceptionHandler(Exception.class)
	@ResponseBody
	protected abstract String handlerException(Exception e);
	
	protected String toJson(Object obj){
		GsonBuilder gb = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss");
		gb.registerTypeHierarchyAdapter(HibernateProxy.class,new JsonSerializer<HibernateProxy>(){
			public JsonElement serialize(HibernateProxy src,Type typeOfSrc, JsonSerializationContext context) {
				return null;
			}
		});
		gb.registerTypeHierarchyAdapter(PersistentList.class,new JsonSerializer<PersistentList>(){
			public JsonElement serialize(PersistentList src,Type typeOfSrc, JsonSerializationContext context) {
				return null;
			}
		});
		String json = gb.serializeNulls().create().toJson(obj);
		System.out.println("Json:"+json);
		return json;
	}
	
	/**
	 * 获取session中后台用户
	 * @param session session会话
	 * @return 登录用户
	 */
	protected User sessionUser(HttpSession session){
		return (User)session.getAttribute("user");
	}
}
